<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password');
	
	public $timestamps = false;
	
	public static $rules = array(
		'name'=>'required|alpha_spaces|min:2',
		'surname'=>'required|alpha_spaces|min:2',
		'username'=>'required|unique:users',
		'password'=>'required|alpha_num|between:4,12|confirmed',
		'password_confirmation'=>'required|alpha_num|between:4,12'
	);
	
	public static $updatePasswordRules = array(
		'currentPassword' => 'required',
		'password'=>'required|alpha_num|between:4,12|confirmed',
		'password_confirmation'=>'required|alpha_num|between:4,12',
	);

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->getKey();
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->password;
	}

	/**
	 * Get the e-mail address where password reminders are sent.
	 *
	 * @return string
	 */
	public function getReminderEmail()
	{
		return $this->email;
	}
	
	public function privileges() {
		return $this->belongsToMany('Privilege', 'users_privileges');
	}
	
	public function hasPrivilege($key) {
		return $this->privileges()->where('key', '=', $key)->count() > 0;
	}
	
	public function isDeletable() {
		$result = DB::selectOne("
			SELECT
				COUNT(*) as total
			FROM (
				SELECT user_id FROM products
				UNION
				SELECT user_id FROM components
				UNION
				SELECT user_id FROM order_component_logs
				UNION
				SELECT user_id FROM order_component_logs
			) AS relations
			WHERE 
				user_id = :userId		
			", 
			array('userId' => $this->id)
		);
		
		return $result->total === 0;
	}

}